// 重放 POST 以捕获响应内容
// 监听网页请求（因为CORS限制所以只读取到了请求体） -> 用请求头重放 -> 监听这个重放的响应
let success = false;
let capturedRequest = null;
let originalOpen = XMLHttpRequest.prototype.open;
let originalSend = XMLHttpRequest.prototype.send;
let originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

XMLHttpRequest.prototype.open = function(method, url) {
    this.requestMethod = method;
    this.requestUrl = url;
    this.requestHeaders = {};
    originalOpen.apply(this, arguments);
};

XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
    this.requestHeaders[header] = value;
    originalSetRequestHeader.apply(this, arguments);
};

XMLHttpRequest.prototype.send = function(body) {
    const xhr = this;
    if (xhr.requestUrl.includes('/getCourseStudyProcess')) {
        xhr.addEventListener('load', function() {

            try {

                const response = JSON.parse(xhr.responseText);
                if (response.success && response.result && response.result.length > 0) {
                    const { userId, courseCatalogId } = response.result[0];
                    // sessionStorage.setItem('cpmaUserId', userId);
                    // sessionStorage.setItem('cpmaCatalogId', courseCatalogId);
                    // console.log('获取到userId:', userId);
                    // console.log('获取到courseCatalogId:', courseCatalogId);
                    
                    // const courseId = window.location.href.match(/\/onlineStudy\/([^/?]+)/)[1];
                    // console.log('获取到courseId:', courseId);
                    
                    capturedRequest = {
                        method: xhr.requestMethod,
                        // 把原请求的 URL 中的 "getCourseStudyProcess?..." 部分replace成 "calcStudyProcess"，也就是把带查询字符串的旧接口地址改成一个新的（不带 query 的）接口地址，便于随后用这个新 URL 发 POST 或重放请求。
                        url: xhr.responseURL.replace(/getCourseStudyProcess\?.*$/, "calcStudyProcess"),
                        requestBody: { courseId: courseId, catalogId: courseCatalogId, userId: userId, viewProcess: 1 },
                        requestHeaders: xhr.requestHeaders
                    };
                    // console.log('Captured request:', capturedRequest);
                    replayRequest();
                    setTimeout(() => {
                        localStorage.setItem('refreshCourseDetailPage', true);
                        success = true;
                        history.back(); // 或者 window.history.back();
                        // window.location.href = window.location.href + '?t=' + new Date().getTime();
                    }, 500);

                }
            } catch (e) {
                console.error('解析响应失败:', e);
            }

        });
    }
    originalSend.apply(xhr, arguments);
};

// 用 GM_xmlhttpRequest 重放请求通常能绕过浏览器 CORS/opaque 限制，拿到响应内容
function replayRequest() {
    if (!capturedRequest) return;

    const headers = capturedRequest.requestHeaders || {};
    headers['Content-Type'] = 'application/json';

    let bodyToSend = capturedRequest.requestBody;
    if (typeof bodyToSend === 'string') {
        try {
            bodyToSend = JSON.parse(bodyToSend);
        } catch (e) {
            console.error('Failed to parse request body as JSON. Sending as is.');
        }
    }

    // console.log('Replaying request:', { method: capturedRequest.method, url: capturedRequest.url, headers: headers, body: bodyToSend });

    GM_xmlhttpRequest({
        method: 'POST',
        url: capturedRequest.url,
        data: JSON.stringify(bodyToSend),
        headers: headers,
        onload: function(response) {
            //console.log('Request replayed. Response:', response);
            try {

                const responseData = JSON.parse(response.responseText);
                console.log(responseData)

            } catch (e) {
                console.error('Failed to parse response:', e);
                setTimeout(replayRequest, 5000);
            }
        },
        onerror: function(error) {
            console.error('Request replay failed:', error);
            setTimeout(replayRequest, 5000);
        }
    });
}